package com.example.demo.thread;

import com.example.demo.pojo.Product;
import com.example.demo.service.ProductService;
import com.example.demo.util.SpringUtil;
import lombok.Setter;

import java.util.List;

public class Depository {
    private ProductService productService;

    private int capacity;

    @Setter
    private int size = 0;

    public Depository(int capacity) {
        productService = SpringUtil.getApplicationContext().getBean(ProductService.class);
        this.capacity = capacity;
    }

    public synchronized void product(int id, int count) throws InterruptedException {
        while (count > 0) {
            size = productService.getOne(id).getStock();
            if (size >= capacity)
                wait();
            size = productService.getOne(id).getStock();
            //真实生产数量
            int realcount = (capacity - size) >= count ? count : (capacity - size);

            System.out.print(Thread.currentThread().getName() + "--本次想要生产：" + count + ",本次实际生产:" + realcount);
            //下次生产数量
            count = count - realcount;
            //仓库剩余
            size += realcount;
            List<Product> products = productService.load();
            for (Product product : products) {
                if (product.getId() == id) {
                    product.setStock(size);
                }
            }
            productService.store(products);
            System.out.println(",下次想要生产：" + count + ",仓库真实容量：" + size);
            notifyAll();
        }
    }

    public synchronized void consume(int id, int count) throws InterruptedException {
        while (count > 0) {
            size = productService.getOne(id).getStock();
            if (size <= 0)
                wait();
            size = productService.getOne(id).getStock();
            //真实消费数量
            int realcount = (size >= count) ? count : size;
            System.out.print(Thread.currentThread().getName() + "--本次想要消费:" + count + ",本次真实消费：" + realcount);

            //下次消费数量
            count = count - realcount;
            //仓库剩余
            size -= realcount;
            List<Product> products = productService.load();
            for (Product product : products) {
                if (product.getId() == id) {
                    product.setStock(size);
                }
            }
            productService.store(products);
            System.out.println("下次想要消费：" + count + "，仓库剩余：" + size);
            notify();
        }
    }
}
